import clsx from "clsx";
import {
  data,
  Links,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
  useRouteLoaderData,
} from "@remix-run/react";
import type { LinksFunction, LoaderFunction } from "@remix-run/node";
import { ThemeProvider, useTheme, PreventFlashOnWrongTheme, Theme } from 'remix-themes';
import { themeSessionResolver } from './sessions.server';

import i18nServer, { i18nCookie } from "./i18n/i18n.server";
import { useTranslation } from "react-i18next";
import { useChangeLanguage } from 'remix-i18next/react';

import "./tailwind.css";

export const links: LinksFunction = () => [
  { rel: "preconnect", href: "https://fonts.googleapis.com" },
  {
    rel: "preconnect",
    href: "https://fonts.gstatic.com",
    crossOrigin: "anonymous",
  },
  {
    rel: "stylesheet",
    href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap",
  },
];

export const loader: LoaderFunction = async ({ request }) => {
  const { getTheme } = await themeSessionResolver(request);
  const locale = await i18nServer.getLocale(request);
  let theme = getTheme()
  if (!theme) {
    theme = Theme.LIGHT
  }
  return data(
    {
      theme, locale
    },
    { headers: { "Set-Cookie": await i18nCookie.serialize(locale) } },
  )
};

export function Layout({ children }: { children: React.ReactNode }) {
  const data = useRouteLoaderData<typeof loader>("root");
  const locale = data.locale;
  const { i18n } = useTranslation();
  useChangeLanguage(locale);

  return (
    <ThemeProvider specifiedTheme={data.theme} themeAction="/action/set-theme">
      <InnerLayout locale={locale} dir={i18n.dir()} ssrTheme={Boolean(data.theme)}>{children}</InnerLayout>
    </ThemeProvider>
  );
}

function InnerLayout({
  locale,
  dir,
  ssrTheme,
  children
}: {
  locale: string,
  dir: string,
  ssrTheme: boolean,
  children: React.ReactNode
}) {
  const [theme] = useTheme();
  return (
    <html lang={locale ?? "en"} dir={dir ?? ""} data-theme={clsx(theme)}>
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <Meta />
        <PreventFlashOnWrongTheme ssrTheme={ssrTheme} />
        <Links />
      </head>
      <body>
        {children}
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}

export default function App() {
  return <Outlet />;
}
